<template>
	<div class="main">
		<div class="main-search">
			<el-form :model="queryParams" ref="queryForm" :inline="true" label-width="114px">
				<el-form-item label="知识点编号" prop="knowledgePointsNo">
					<el-input
						v-model="queryParams.knowledgePointsNo"
						placeholder="请输知识点编号"
						clearable
						style="width: 200px"
						@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item label="关联题目ID" prop="exercisesNo">
					<el-input
						v-model="queryParams.exercisesNo"
						placeholder="关联题目ID"
						clearable
						style="width: 200px"
						@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item prop="course">
					<aselect title="关联课程" @clear="courseReturn_" :course="queryParams.courseSectionNo_" @change="courseReturn_"></aselect>
				</el-form-item>
				<el-form-item label="考试频度" prop="frequencys">
					<el-select multiple style="width: 200px" v-model="queryParams.frequencys">
						<el-option
							v-for="(item, index) in frequencyList"
							:key="index"
							:label="item.value"
							:value="item.key"
						/>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button :icon="Search" type="primary" @click="handleQuery">搜索</el-button>
				</el-form-item>
			</el-form>
		</div>
		<el-row :gutter="10" style="margin-bottom: 10px">
			<el-col :span="1.5">
				<el-button
					type="primary"
					@click="handleAdd"
				>新增知识点
				</el-button>
			</el-col>
		</el-row>

		<el-table class="cl-table" v-loading="loading" :data="knowledgeList">
			<el-table-column label="知识点编号" align="center" prop="knowledgePointsNo" />
			<el-table-column label="知识点名称" align="center" prop="name"
							 :show-overflow-tooltip="true" />
			<el-table-column label="知识点定义" align="center" prop="definition" :show-overflow-tooltip="true">
				<template #default="scope">
					{{scope.row.definition}}
				</template>
			</el-table-column>
			<el-table-column label="知识点级别" align="center" prop="level"
							 :show-overflow-tooltip="true">
				<template #default="scope">
					{{scope.row.level}}级
				</template>
			</el-table-column>
			<el-table-column label="考试频度" align="center" prop="frequency">
				<template #default="scope">
					{{frequencyList.find(item=>item.key==scope.row.frequency).value}}
				</template>
			</el-table-column>
			<el-table-column label="直接前序知识点" align="center" prop="remark" :show-overflow-tooltip="true">
				<template #default="scope">
					<el-link type="primary" @click="() => { openEcharts(scope.row) }">{{scope.row.prePointsNum?scope.row.prePointsNum:0}}个</el-link>
				</template>
			</el-table-column>
			<el-table-column label="关联课程章节" align="center">
				<template #default="scope">
					<el-link type="primary" @click="() => { jumpCourse(scope.row) }">{{scope.row.courseNum}}个</el-link>
				</template>
			</el-table-column>
			<el-table-column label="关联题目" align="center" prop="exercisesNo" />

			<el-table-column  fixed="right" label="操作" align="center" width="200" class-name="small-padding fixed-width">
				<template #default="scope">
					<el-button type="primary" link @click="showRelated(scope.row)">
						设置直接前序
					</el-button>
					<el-icon class="ams-edit" @click="handleUpdate(scope.row)">
						<Edit />
					</el-icon>
					<el-icon class="ams-delete" @click="handleDelete(scope.row)">
						<Delete />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			v-model:current-page="queryParams.pageNum"
			:page-size="queryParams.pageSize"
			:total="total"
			background
			layout="total, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		/>
		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="title" v-model="open" width="50%" append-to-body>
			<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="知识点名称" prop="name"
									  :rules="{required: true, message: '请输入知识点名称', trigger: 'change'}">
							<el-input v-model.trim="form.name" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24" class="latex-item">
						<el-form-item label="知识点定义" prop="definition"
									  :rules="{required: true, message: '请输入知识点定义', trigger: 'change'}">
							<el-input v-model.trim="form.definition" />
						</el-form-item>
						<img class="latex" @click="editorShow" src="../../../assets/images/latex/cx.png" />
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="考试频度" prop="frequency">
							<el-select v-model="form.frequency">
								<el-option
									v-for="(item, index) in frequencyList"
									:key="index"
									:label="item.value"
									:value="item.key"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="showEditor">
					<el-col :span="24">
						<editor :data="form.definition" @close="closeEditer" ref="editorRef" />
					</el-col>
				</el-row>
				<el-row>
					<template v-for="(item,index) in form.courseNoStrs">
						<aselect @clear="clearCourse" @change="($)=>courseReturn($,index)" :course="item" @remove="removeItem" @add="addItem" title="关联课程">
							<el-button
								v-if="index === 0"
								link
								:icon="Plus"
								@click="addItem"
							/>
							<el-button
								link
								type="danger"
								v-else
								:icon="Delete"
								@click="removeItem(index)"
							/>
						</aselect>
					</template>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">保存</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog top="40px" title="设置直接前序" @close="cancelRelated" v-if="openRelated" v-model="openRelated" width="90%" append-to-body>
			<related @selected="getList" :current="current" :frequencyList="frequencyList" actionType="knowledge" ref="relatedRef" />
		</el-dialog>

		<el-dialog title="直接前序知识点图谱" @close="cancelEchart" v-if="openEchart" v-model="openEchart"  width="50%" append-to-body>
			<graph action="direct" :direct="direct"></graph>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Search, View, Plus, Delete, Edit } from '@element-plus/icons-vue';
import aselect from '../../common/aselect/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import editor from '../../question/common/editor.vue';
import related from '../../question/common/related.vue';
import graph from '../components/index.vue'
import { useCool } from '/@/cool/hooks';
import {
	getFrequencyCombobox,
	searchKnowledgePoints,
	addKnowledgePoints,
	delKnowledgePointsById,
	modifyKnowledgePoints,
	getKnowledgePointsById
} from '/@/api/knowledge/index';

const { router } = useCool();
const editorRef = ref<InstanceType<typeof editor> | null>(null);
const relatedRef = ref<InstanceType<typeof related> | null>(null);
// 数据定义
const loading = ref(false);
let current = reactive({})
let knowledgeList = ref([]);
const title = ref('');
const open = ref(false);
const openEchart = ref(false);
const direct = reactive({
	chartName:'',
	knowledgePointsNo:'',
	chartStatus: ''
});

const frequencyList = ref([]);
const openRelated = ref(false);
const showEditor = ref(false);

const queryForm = ref<FormInstance>();
const formRef = ref<FormInstance>();
// 编辑器实例，必须用 shallowRef

const total = ref(0);
const queryParams = reactive({
	"courseNo": "",
	"courseSectionNo": "",
	"courseSectionNo_": [],
	"exercisesNo": "",
	"frequencys": [],
	"knowledgePointsNo": "",
	"pageNum": 1,
	"pageSize": 5
});
let form = reactive({
	"courseNoStrs": [{}],
	"definition": "",
	"frequency": [],
	"id": 0,
	"knowledgePointsNo": "",
	"name": ""
});

const rules = reactive({});
const addItem = () => {
	form.courseNoStrs.push({})
};
const removeItem = (index:number) => {
	form.courseNoStrs.splice(index, 1);
};

const getList = async () => {
	if (queryParams.courseSectionNo_.length>0) {
		queryParams.courseSectionNo = queryParams.courseSectionNo_[0];
	}
	let res_ = await searchKnowledgePoints(queryParams);
	knowledgeList.value = res_.data.list;
	total.value = res_.data.total;
};

const cancel = () => {
	open.value = false;
	reset();
};

const reset = () => {
	formRef.value?.resetFields();
	form["courseNoStrs"] = [{}];
	form["definition"] = "";
	form["frequency"] = [];
	form["id"] = 0;
	form["knowledgePointsNo"] = "";
	form["name"] = "";
};

const handleQuery = () => {
	queryParams.pageNum = 1;
	getList();
};

const resetQuery = () => {
	queryForm.value?.resetFields();
	handleQuery();
};

const handleAdd = () => {
	reset();
	open.value = true;
	title.value = '新增知识点';
};
const transformItem = (item) => {
	return {
		courseNoStrs: [{courseNoStr: item.courseNoStr}],
		definition: item.definition,
		frequency: item.frequency,
		id: item.id,
		knowledgePointsNo: item.knowledgePointsNo,
		name: item.name
	};
}
const handleUpdate = async (row: any) => {
	reset();
	open.value = true;
	title.value = '修改知识点';
	let param = transformItem(row)
	Object.assign(form, param);
	let res = await getKnowledgePointsById(form.id);

	if (res && res.data) {

		form.courseNoStrs = [] ;
		res.data.courseNoStrs.forEach((item, index) => {
			form.courseNoStrs.push({
				courseNoStr: item
			})
		})

	}
};
const extractCourseNoStrs = (data) => {
	if (!data || !Array.isArray(data.courseNoStrs)) {
		return [];
	}
	return data.courseNoStrs.map(item => item.courseNoStr);
}
const checkCourseNoStrs = (courseNoStrs) => {
	// 检查参数是否为数组
	if (!Array.isArray(courseNoStrs)) {
		return false;
	}

	// 遍历数组中的每个元素
	for (const item of courseNoStrs) {
		// 检查元素是否为对象类型且不为 null
		if (typeof item !== 'object' || item === null) {
			return false;
		}

		// 检查对象是否为空（没有自有属性）
		if (Object.keys(item).length === 0) {
			return false;
		}
	}

	// 所有元素都通过检查，返回 true
	return true;
}
const submitForm = () => {
	formRef.value?.validate(async (valid) => {
		if (valid) {
			let params = {};
			for(let key in form) {
				if (key == 'courseNoStrs') {
					params[key] = extractCourseNoStrs(form)
				} else {
					params[key] = form[key];
				}
			}
			let flag = checkCourseNoStrs(form.courseNoStrs);
			if (flag) {
				let res = (title.value === '修改知识点')? await modifyKnowledgePoints(params):await addKnowledgePoints(params);
				if (res.code==200) {
					ElMessage.success((title.value === '修改知识点' ? '修改知识点' : '新增知识点') + '成功');
					await getList();
				}
				open.value = false;
			}else {
				ElMessage.warning('请选择课程章节！')
			}
		}
	});
};

const handleDelete = async (row) => {
	await ElMessageBox.confirm('是否确认删除？');
	await delKnowledgePointsById(row.id);
	await getList();
};

const showRelated = (item) => {
	openRelated.value = true;
	Object.assign(current,item,{pointsNo:item.knowledgePointsNo});
}
const cancelRelated = () => {
	openRelated.value = false;
	Object.assign(current,{});
	getList()
}
const cancelEchart = () => {
	openEchart.value = false;
	getList()
}
const editorShow = () => {
	showEditor.value = true;
}
const closeEditer = (code:any) => {
	showEditor.value = false;
	if (code) {
		form.definition = code;
	}
}
const clearCourse = () => {
	form.courseNoStrs = [{}];
}
const courseReturn = (param,index) => {
	form.courseNoStrs[index].courseNoStr = param;
}
const courseReturn_ = (params) => {
	if (params) {
		let list = params.split(",");
		queryParams.courseSectionNo = list.length > 0?list[list.length - 1]:'';
	} else {
		queryParams.courseSectionNo = '';
	}
}
const handleSizeChange = async (val: number) => {
	queryParams.pageSize = val;
	await getList();
}
const handleCurrentChange = async (val: number) => {
	queryParams.pageNum = val;
	await getList();
}
// 生命周期
onMounted(async () => {
	let res = await getFrequencyCombobox();
	frequencyList.value = res.data;
	await getList();
});

const jumpCourse = (param) => {
	router.push({
		path: '/course/list',
		query: Object.assign({}, {id:param.id}, { type: 'detail' })
	})
}
const openEcharts = (param) => {
	openEchart.value = true;
	direct.chartName = param.chartName;
	direct.knowledgePointsNo = param.knowledgePointsNo;
	direct.chartStatus = param.chartStatus;
}

</script>
<style scoped lang="scss">
.knowledge-tag{
	cursor: pointer;
	margin-right: 16px;
	margin-bottom: 12px
}

</style>
